package com.ruoyi.note.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.note.domain.NoteCategory;
import com.ruoyi.note.mapper.NoteCategoryMapper;
import com.ruoyi.note.mapper.NoteDailyMapper;
import com.ruoyi.note.mapper.NoteDocumentMapper;
import com.ruoyi.note.service.INoteCategoryService;

/**
 * 笔记分类Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-01-22
 */
@Service
public class NoteCategoryServiceImpl implements INoteCategoryService 
{
    @Autowired
    private NoteCategoryMapper noteCategoryMapper;

    @Autowired
    private NoteDailyMapper noteDailyMapper;

    @Autowired
    private NoteDocumentMapper noteDocumentMapper;

    /**
     * 查询笔记分类
     * 
     * @param categoryId 笔记分类主键
     * @return 笔记分类
     */
    @Override
    public NoteCategory selectNoteCategoryByCategoryId(Long categoryId)
    {
        return noteCategoryMapper.selectNoteCategoryByCategoryId(categoryId);
    }

    /**
     * 查询笔记分类列表
     * 
     * @param noteCategory 笔记分类
     * @return 笔记分类
     */
    @Override
    public List<NoteCategory> selectNoteCategoryList(NoteCategory noteCategory)
    {
        return noteCategoryMapper.selectNoteCategoryList(noteCategory);
    }

    /**
     * 查询笔记分类树结构
     * 
     * @param noteCategory 笔记分类
     * @return 笔记分类集合
     */
    @Override
    public List<NoteCategory> selectNoteCategoryTree(NoteCategory noteCategory)
    {
        return noteCategoryMapper.selectNoteCategoryTree(noteCategory);
    }

    /**
     * 构建前端所需要树结构
     * 
     * @param categories 分类列表
     * @return 树结构列表
     */
    @Override
    public List<NoteCategory> buildCategoryTree(List<NoteCategory> categories)
    {
        List<NoteCategory> returnList = new ArrayList<NoteCategory>();
        List<Long> tempList = categories.stream().map(NoteCategory::getCategoryId).collect(Collectors.toList());
        for (NoteCategory category : categories)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(category.getParentId()))
            {
                recursionFn(categories, category);
                returnList.add(category);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = categories;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     * 
     * @param categories 分类列表
     * @return 下拉树结构列表
     */
    @Override
    public List<Ztree> initZtree(List<NoteCategory> categories)
    {
        return initZtree(categories, null, false);
    }

    /**
     * 对象转分类树
     *
     * @param categoryList 分类列表
     * @param roleCategoryList 角色已存在菜单列表
     * @param permsFlag 是否需要显示权限标识
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<NoteCategory> categoryList, List<String> roleCategoryList, boolean permsFlag)
    {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        boolean isCheck = StringUtils.isNotNull(roleCategoryList);
        for (NoteCategory category : categoryList)
        {
            Ztree ztree = new Ztree();
            ztree.setId(category.getCategoryId());
            ztree.setpId(category.getParentId());
            ztree.setName(category.getCategoryName());
            ztree.setTitle(category.getCategoryName());
            if (isCheck)
            {
                ztree.setChecked(roleCategoryList.contains(category.getCategoryId() + "_" + category.getParentId()));
            }
            ztrees.add(ztree);
        }
        return ztrees;
    }

    /**
     * 新增笔记分类
     * 
     * @param noteCategory 笔记分类
     * @return 结果
     */
    @Override
    public int insertNoteCategory(NoteCategory noteCategory)
    {
        return noteCategoryMapper.insertNoteCategory(noteCategory);
    }

    /**
     * 修改笔记分类
     * 
     * @param noteCategory 笔记分类
     * @return 结果
     */
    @Override
    public int updateNoteCategory(NoteCategory noteCategory)
    {
        return noteCategoryMapper.updateNoteCategory(noteCategory);
    }

    /**
     * 批量删除笔记分类
     * 
     * @param categoryIds 需要删除的笔记分类主键
     * @return 结果
     */
    @Override
    public int deleteNoteCategoryByCategoryIds(String categoryIds)
    {
        Long[] categoryIdArray = Convert.toLongArray(categoryIds);
        for (Long categoryId : categoryIdArray)
        {
            checkCategoryExistNote(categoryId);
            checkCategoryExistDocument(categoryId);
            if (hasChildByCategoryId(categoryId))
            {
                throw new ServiceException("存在子分类,不允许删除");
            }
        }
        return noteCategoryMapper.deleteNoteCategoryByCategoryIds(categoryIdArray);
    }

    /**
     * 删除笔记分类信息
     * 
     * @param categoryId 笔记分类主键
     * @return 结果
     */
    @Override
    public int deleteNoteCategoryByCategoryId(Long categoryId)
    {
        checkCategoryExistNote(categoryId);
        checkCategoryExistDocument(categoryId);
        if (hasChildByCategoryId(categoryId))
        {
            throw new ServiceException("存在子分类,不允许删除");
        }
        return noteCategoryMapper.deleteNoteCategoryByCategoryId(categoryId);
    }

    /**
     * 校验分类名称是否唯一
     * 
     * @param noteCategory 分类信息
     * @return 结果
     */
    @Override
    public boolean checkCategoryNameUnique(NoteCategory noteCategory)
    {
        Long categoryId = StringUtils.isNull(noteCategory.getCategoryId()) ? -1L : noteCategory.getCategoryId();
        NoteCategory info = noteCategoryMapper.checkCategoryNameUnique(noteCategory.getCategoryName(), noteCategory.getParentId(), categoryId);
        if (StringUtils.isNotNull(info) && info.getCategoryId().longValue() != categoryId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 是否存在分类子节点
     * 
     * @param categoryId 分类ID
     * @return 结果
     */
    public boolean hasChildByCategoryId(Long categoryId)
    {
        int result = noteCategoryMapper.selectChildrenCountByParentId(categoryId);
        return result > 0 ? true : false;
    }

    /**
     * 查询分类是否存在笔记
     * 
     * @param categoryId 分类ID
     */
    public void checkCategoryExistNote(Long categoryId)
    {
        int result = noteDailyMapper.selectNoteCountByCategoryId(categoryId);
        if (result > 0)
        {
            throw new ServiceException("分类存在笔记,不允许删除");
        }
    }

    /**
     * 查询分类是否存在文档
     * 
     * @param categoryId 分类ID
     */
    public void checkCategoryExistDocument(Long categoryId)
    {
        int result = noteDocumentMapper.selectDocumentCountByCategoryId(categoryId);
        if (result > 0)
        {
            throw new ServiceException("分类存在文档,不允许删除");
        }
    }

    /**
     * 递归列表
     * 
     * @param list 分类表
     * @param t 子节点
     */
    private void recursionFn(List<NoteCategory> list, NoteCategory t)
    {
        // 得到子节点列表
        List<NoteCategory> childList = getChildList(list, t);
        t.setChildren(childList);
        for (NoteCategory tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<NoteCategory> getChildList(List<NoteCategory> list, NoteCategory t)
    {
        List<NoteCategory> tlist = new ArrayList<NoteCategory>();
        Iterator<NoteCategory> it = list.iterator();
        while (it.hasNext())
        {
            NoteCategory n = (NoteCategory) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getCategoryId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<NoteCategory> list, NoteCategory t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }
}